import Vue from "vue";
import Vuex from "vuex";
import createPersistedState from "vuex-persistedstate"
import { login, getuserhistory } from '@api/login'
Vue.use(Vuex);
import { Toast, Dialog } from "vant";
import route from '../router/index'
Vue.use(Toast);
Vue.use(Dialog);


// function Mysplice(group,group2){
//   group.forEach((v) => {
//     group2.forEach((p, i) => {
//       if (v.titleId == p.titleId) {
//         group2.splice(i, 1);
//       }
//     });
//   });
// }

function Mysplice(group, group2) {
  group.forEach((v) => {
    group2.forEach((p, i) => {
      if (v.titleId == p.titleId) {
        group2.splice(i, 1);
      }
    });
  });
}


export default new Vuex.Store({
  namespaced: false, //关闭
  state: {
    isshowback:false,
    title:"",
    homeshow:true,
    rankTime:'阅读时间',
    startTime:0,
    endTime:0,

    rankTime: '阅读时间',
    startTime: 0,
    endTime: 0,

    // 记录 阅读历史
    recordArr: [],
    newStatus: -1,
    // 加入 书架
    groupName: "默认书架",
    bookrackArr: { '默认书架': { group: [] } },

    //夜间日间
    ye: true,

    XselecedIndex: 2,

    history:{},
    history2: {
    },

    // 字体大小
    fonsize: 4
  },
  getters: {
    gettitle(state){
      return state.title
    },
    getIsShowBack(state){
      return  state.isshowback
    },
  
    bookrackLength(state) {
      return Object.keys(state.bookrackArr).length
    },
    getfonsize(state) {
      return state.fonsize
    },

     getye(state){
        return  state.ye
     },
     contentfonsize(state){
        return  state.fonsize*0.1
     },
     XselecedIndex(state){
        return  state.XselecedIndex
     },
     gethistory(state){
        return   state.history2
     },
     gethomeshow(state){
       return   state.homeshow
     }

  },
  mutations: {
    CHANGE_TITLE(state,title){
      state.title = title
    },

    CHANGDE_BACK(state,isT){
      console.log("修改值");
      state.isshowback = isT
      console.log(state);
    },

    //底部是否显示
    CHANGE_HOMESHOW(state , data){
      state.homeshow = data
    },

    //  更改全局字体大小
    CHANGE_FONSIZE(state, value) {
      this.state.fonsize = value
    },

    CHANGE_YE(state) {
      this.state.ye = !this.state.ye
    },

    CHANGDE_INDEX(state, value) {
      this.state.ye = false
      this.state.XselecedIndex = value
    },
    //  更新浏览记录  登录的时候 整个覆盖 
    CHANGE_HISTORY(state, value) {
      console.log("登录更新历史 记录");
      state.history = value

},
//  本地更新 浏览记录   浏览的时候 覆盖单个值
  CHANGE_LOCATION_HISTORY(state,value){
      console.log( "vuex历史记录",state,value);
      state.history2[value.id] = value.sort
      console.log(state);
  },
     // 删除我的书架 上的书
     deleteMybook(state, checked) {

      let oldGroup = state.bookrackArr[state.groupName].group
      let newGroup = checked.map(v => oldGroup[v])
      Mysplice(newGroup, oldGroup)
    },
    // 新增分组
    Addgrouping(state, { groupName, group }) {
      let oldName = state.bookrackArr[state.groupName];
      if (state.groupName == groupName) {
        Dialog.alert({
          message: "不需要添加到相同的分组中",
        })
        return;
      }
      if (state.bookrackArr[groupName]) {
        console.log('分组已经存在');
        if (state.bookrackArr[groupName].group.length) {
          console.log('有长度');
          state.bookrackArr[groupName].group.forEach((v) => {
            group.forEach((p, i) => {
              if (v.titleId != p.titleId) {
                state.bookrackArr[groupName].group.unshift(p);
                Mysplice(group, oldName.group)
                return;
              } else {
                console.log('书已经存在');
              }
            });
          });
        } else {
          console.log('没有长度');
          state.bookrackArr[groupName].group.unshift(...group);
          Mysplice(group, oldName.group)
        }

      } else {
        state.bookrackArr[groupName] = { group };
        Mysplice(group, oldName.group)
      }
    },
    // 加入到书架
    AddbookRack(state, bookrackArr) {
      let i = state.bookrackArr[state.groupName].group.findIndex(
        (v) => v.titleId == bookrackArr.titleId
      );
      if (i < 0) {
        state.groupName = "默认书架";
        state.bookrackArr[state.groupName].group.unshift(bookrackArr);
        Toast("成功加入");
      } else {
        Toast("书架已有这本书了");
      }
    },
    // 时间排序
    setRankTime(state, text) {
      state.rankTime = text
    },

    // 历史记录
    StoreRecord(state, readRecord) {
      let index = state.recordArr.findIndex(item => item.titleId == readRecord.titleId)
      if (index >= 0) {
        state.recordArr.splice(index, 1)
      }
      state.recordArr.unshift(readRecord);
    },

    // 记录阅读文章的总时间
    SetReadtime(state, status = true) {
      let time = Date.now();
      // 进入阅读时                            退出阅读时
      status ? (state.startTime = time) : (state.endTime = time);
    },
  },
  actions: {
    async login(store, values) {
      let { data } = await login(values)

      if (!data) {
        return {
          code: 40004,
          message: "账号密码错误"
        }
      }
      // data 可以得到用户信息  token
      localStorage.setItem('token', data.token)
      localStorage.setItem('expiresIn', parseInt(Date.now() / 1000 + data.expiresIn))
      //  返回的有效多少秒  
      localStorage.setItem('userinfo', JSON.stringify(data.userinfo))
      localStorage.setItem('userPD', JSON.stringify(values))

      let result = await getuserhistory()
      console.log("返回的浏览记录", result.data.history);
      store.commit('CHANGE_HISTORY', result.data.history)
      return {
        code: 20000,
        message: "登录成功"
      }
    }
  },


  //  防止数据刷新了 被丢失了 ,  这个插件是将数据实时存放在 本地存储, 让VUEx 的数据与本地存储同步 
  plugins: [createPersistedState()]
});
